package com.andf.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.andf.common.page.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Json 转换
 * @author liujianj
 * 
 */
public class ToGson {
	
	/**
	 * 返回列表集合
	 * @param listResult 查询列表
	 * @param countResult 总结果行数
	 * @param bf 基础form
	 * @param res HttpServletResponse
	 * @return
	 */	
	public static String pageToJson(List listResult,Integer countResult,BaseForm bf,HttpServletResponse res) {
		Gson gson = getGson();
		Page page  = new Page(bf.rows,bf.page,countResult);
		page.setRows(listResult);
		HttpServletResponse response = res;
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(page));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	/**
	 * 返回单个结果
	 * @param listResult 查询列表
	 * @param res HttpServletResponse
	 * @return
	 */
	public static String ListToJson(List listResult,HttpServletResponse res) {
		Gson gson = getGson();
		HttpServletResponse response = res;
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(listResult));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	/**
	 * 返回单个结果
	 * @param result Object
	 * @param res HttpServletResponse
	 * @return
	 */
	public static String objectToJson(Object result,HttpServletResponse res) {
		Gson gson = getGson();
		HttpServletResponse response = res;
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(result));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	public static String stirngToJson(String result,HttpServletResponse res) {
		HttpServletResponse response = res;
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(result);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	

	/**
	 * 解决gson格式化日期不规范
	 * @return
	 */
	private static Gson getGson(){
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		return gson;
	}
}
